#include<iostream>
using namespace std;
#include"stdTcpServer.h"
#include<unistd.h>
#include"stdShared.h"
#include<cstring>
#include"chatroom.h"
//界面菜单
void interfaceMenu()
{
    cout<<"1、注册"<<endl;
    cout<<"2、登录"<<endl;
    cout<<"3、退出"<<endl;
}
//注册功能
void registerFunc(const stdTcpSocketPtr &client)
{
    string messages;
    string name;
    string password;
    cout << "请输入用户名：";
    fflush(stdout);
    cin >> name;
    cout << "请输入密码：";
    fflush(stdout);
    cin >> password;
    Msg msg;
    memset(&msg, 0, sizeof(msg));
    msg.type = REGESTER;
    strncpy(msg.name, name.c_str(), sizeof(msg.name) - 1);
    strncpy(msg.passwd, password.c_str(), sizeof(msg.passwd) - 1);
    // 将用户名和密码发给服务器
    client->sendMessage(&msg,sizeof(msg));
    
    ReplyMsg recvMsg;
    client->recvMessage(&recvMsg, sizeof(recvMsg));
    if(recvMsg.state_code==REGESTER_SUCESS)
    {
        cout << "注册成功..." << endl;
        
    }
    else if(recvMsg.state_code==REGESTER_USEREXIST)
    {
        cout << "重复注册，用户已存在" << endl;
    }
}
//登录功能
void loginFunc(const stdTcpSocketPtr &client)
{
    string name;
    string password;
    cout << "请输入用户名：";
    fflush(stdout);
    cin >> name;
    cout << "请输入密码：";
    fflush(stdout);
    cin >> password;
    Msg msg;
    memset(&msg, 0, sizeof(msg));
    msg.type = LOGIN;
    strncpy(msg.name,name.c_str(), sizeof(msg.name) - 1);
    strncpy(msg.passwd,password.c_str(), sizeof(msg.passwd) - 1);
    // 将用户名和密码发给服务器
    client->sendMessage(&msg,sizeof(msg));

    ReplyMsg recvMsg;
    client->recvMessage(&recvMsg, sizeof(recvMsg));
    if(recvMsg.state_code==LOGIN_SUCCESS)
    {
        cout << "登录成功" << endl;
        sleep(2);
        system("clear");
        ChatRoom chatroom(client);
        chatroom.ChatEnter();
    }
    else if(recvMsg.state_code==LOGIN_PASSWDERROR)
    {
        cout << "密码错误" << endl;
    }
    else if(recvMsg.state_code==LOGIN_NOUSER)
    {
        cout << "没有该用户，请先注册"<<endl;
    }
}
int main()
{
    //客户端
    stdTcpSocketPtr client=std::make_shared<stdTcpSocket>();
    //连接服务器
    const char *serverIp = "192.168.232.129";
    int ret=client->connectToServer(serverIp, 8080);
    if(ret!=0)
    {
        cout << "connectToServer failed" << endl;
        _exit(-1);
    }
    cout << "连接成功..." <<endl;
    sleep(1);
    system("clear");
    int choice;
    while (1)
    {
        interfaceMenu();
        cout << "请输入你的选项：";
        cin >> choice;
        switch(choice)
        {
        case REGESTER:
            registerFunc(client);
            break;
        case LOGIN:
            loginFunc(client);
            break;
        case EXIT:
            exit(0);
            break;
        }
    }
    return 0;
}